/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.worker.app;

import org.openislands.oi.pojo.dto.NodeDTO;
import org.openislands.oi.pojo.dto.RouteDTO;
import org.openislands.oi.util.ValueCopyUtils;
import org.openislands.oi.worker.manager.WorkerNodeManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@Service
public class NodeService {
    @Resource(type = WorkerNodeManager.class)
    private WorkerNodeManager nodeManager;

    public NodeDTO verifyNode(NodeDTO nodeDTO) {
        if (!nodeManager.myNodeId(nodeDTO.getNodeId())) {
            // add partner node
            nodeManager.verifyNode(ValueCopyUtils.copyProperties(nodeDTO, new NodeDTO(), (s, t) -> {
                t.setRouteDTOList(s.getRouteDTOList().stream()
                        .map(routeDTO -> ValueCopyUtils.copyProperties(routeDTO, new RouteDTO()))
                        .collect(Collectors.toList()));
                return t;
            }));
        }
        return nodeManager.myNodeDTO();
    }

    public Boolean breakNode(NodeDTO nodeDTO) {
        return nodeManager.breakNode(nodeDTO);
    }
}
